﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml;
using LiuYan.Base;
using LiuYan.Interface;
using LiuYan.Service;

namespace LiuYan.Web.Controllers
{
    public class DevelopController : Controller
    {
        //
        // GET: /Develop/

        #region 成为微信开发者
        public void CDevelop()
        {//获取微信消息推送
            if (Request.HttpMethod == "POST")
            {
                PostInput();
            }
            if (string.IsNullOrEmpty(Request.QueryString["echoStr"]))
            {
                Response.End();
            }
            string echoStr = Request.QueryString["echoStr"];
            Response.Write(echoStr);
            if (CheckSignature())
            {
                WriteMess("1");
                if (!string.IsNullOrEmpty(echoStr))
                {
                    WriteMess("2");
                    Response.Write(echoStr);
                    Response.End();
                }
            }
           // return View();
        }
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <returns></returns>
        private bool CheckSignature()
        {
            string signature = Request.QueryString["signature"];
            string timestamp = Request.QueryString["timestamp"];
            string nonce = Request.QueryString["nonce"];
            string[] ArrTmp = { WxEntity.token, timestamp, nonce };
            Array.Sort(ArrTmp); //字典排序　
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            WriteMess(tmpStr + "__" + signature);
            if (tmpStr == signature)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 微信oauth鉴权
        /// <summary>
        /// oauth鉴权获取code
        /// </summary>
        /// <returns></returns>
        //public ActionResult GetOauth(string url)
        //{
        //    var str =Request.Url.ToString();//当前页面url
        //    if (Request["code"] != null)
        //    {
        //        Response.Redirect(url + "&code" + Request["code"]);
        //    }
        //    WxStr.OauthUrl = string.Format(WxStr.OauthUrl, WxStr.appid, Server.UrlEncode(str));
        //    Response.Redirect(WxStr.OauthUrl);
        //    return View();
        //}
        #endregion

        /// <summary>
        /// 获取到事件信息
        /// </summary>
        /// <returns></returns>
        private void PostInput()
        {
            Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            var Wx= Encoding.UTF8.GetString(b);
            WriteMess(Wx);
            ResponseMsg(Wx);
        }

        #region 接收的消息实体类 以及 填充方法
        private class ExmlMsg
        {
            /// <summary>
            /// 本公众账号
            /// </summary>
            public string ToUserName { get; set; }
            /// <summary>
            /// 用户账号
            /// </summary>
            public string FromUserName { get; set; }
            /// <summary>
            /// 发送时间戳
            /// </summary>
            public string CreateTime { get; set; }
            /// <summary>
            /// 发送的文本内容
            /// </summary>
            public string Content { get; set; }
            /// <summary>
            /// 消息的类型
            /// </summary>
            public string MsgType { get; set; }
            /// <summary>
            /// 事件名称
            /// </summary>
            public string EventName { get; set; }
            /// <summary>
            /// 事件ID
            /// </summary>
            public string EventKey { get; set; }

        }
        private ExmlMsg GetExmlMsg(XmlElement root)
        {
            ExmlMsg xmlMsg = new ExmlMsg()
            {
                FromUserName = root.SelectSingleNode("FromUserName").InnerText,
                ToUserName = root.SelectSingleNode("ToUserName").InnerText,
                CreateTime = root.SelectSingleNode("CreateTime").InnerText,
                MsgType = root.SelectSingleNode("MsgType").InnerText,
              
            };
            if (xmlMsg.MsgType.Trim().ToLower() == "text")
            {
                xmlMsg.Content = root.SelectSingleNode("Content").InnerText;
            }
            else if (xmlMsg.MsgType.Trim().ToLower() == "event")
            {
                xmlMsg.EventName = root.SelectSingleNode("Event").InnerText;
                if (xmlMsg.EventName == "CLICK")
                {
                    xmlMsg.EventKey = root.SelectSingleNode("EventKey").InnerText;
                }
            }
            return xmlMsg;
        }
        #endregion

        #region 消息类型适配器
        private void ResponseMsg(string Wx)// 服务器响应微信请求
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Wx);//读取xml字符串
            XmlElement root = doc.DocumentElement;
            ExmlMsg xmlMsg = GetExmlMsg(root);
            string messageType = xmlMsg.MsgType;//获取收到的消息类型。文本(text)，图片(image)，语音等。
            try
            {
                switch (messageType)
                {
                    //当消息为文本时
                    case "text":
                      //  ResponseText(xmlMsg);
                        WriteMess("text");
                        break;
                    case "event": //当消息为事件时
                        WriteMess(xmlMsg.EventKey);
                        WriteMess("event");
                        if (!string.IsNullOrEmpty(xmlMsg.EventName) && xmlMsg.EventName.Trim() == "subscribe")
                        {
                            //刚关注时的事件，用于欢迎词  
                            int nowtime = Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd"));
                            string msg = new ReplyService().GetData().Rows[0]["Content"].ToString();
                            string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName +
                                            "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName +
                                            "]]></FromUserName><CreateTime>" + nowtime +
                                            "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg +
                                            "]]></Content><FuncFlag>0</FuncFlag></xml>";
                            Response.Write(resxml);
                        }
                        else
                        {
                            int nowtime = Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd"));
                            try
                            {
                                var table = new BaseService().GetOneData(Convert.ToInt32(xmlMsg.EventKey), "TB_ImgArticle");
                               // string resxml = "<xml>" +
                               //"<ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName>" +
                               //"<FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName>" +
                               //"<CreateTime>" + nowtime + "</CreateTime>" +
                               //"<MsgType><![CDATA[news]]></MsgType>" +
                               //"<ArticleCount>1</ArticleCount>" +
                               //"<Articles>" +
                               //"<item>" +
                               //"<Title><![CDATA[" + table.Rows[0]["Title"] + "]]></Title> " +
                               //"<Description><![CDATA[文字内容]]></Description>" +
                               //"<PicUrl><![CDATA[" +"http://www.Wx.lzfbk.com"+ table.Rows[0]["Img"] + "]]></PicUrl>" +
                               //"<Url><![CDATA[http://www.lzfbk.com]]></Url>" +
                               //"</item>" +
                               //"</Articles>" +
                               //"</xml> ";

                                string resxml = "<xml>" +
                                "<ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName>" +
                                "<FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName>" +
                                "<CreateTime>" + nowtime + "</CreateTime>" +
                                "<MsgType><![CDATA[news]]></MsgType>" +
                                "<ArticleCount>1</ArticleCount>" +
                                "<Articles>" +
                                "<item>" +
                                "<Title><![CDATA[" + table.Rows[0]["Title"] + "]]></Title> " +
                                "<Description><![CDATA[" + table.Rows[0]["Des"] + "]]></Description>" +
                                "<PicUrl><![CDATA[" +"http://www.weixin.lzfbk.com"+ table.Rows[0]["Img"] + "]]></PicUrl>" +
                                "<Url><![CDATA[" + table.Rows[0]["Url"] + "]]></Url>" +
                                "</item>" +
                                "</Articles>" +
                                "</xml> ";
                                //WriteMess(resxml);
                                Response.Write(resxml);
                            }
                            catch (Exception e)
                            {
                                WriteMess(e.ToString());
                                string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName +
                                                   "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName +
                                                   "]]></FromUserName><CreateTime>" + nowtime +
                                                   "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + "获取信息失败！" +
                                                   "]]></Content><FuncFlag>0</FuncFlag></xml>";
                                Response.Write(resxml);
                            }
                        }
                        break;
                    case "image":
                        break;
                    case "voice":
                        break;
                    case "vedio":
                        break;
                    case "location":
                        break;
                    case "link":
                        break;
                    default:
                        break;
                }
                Response.End();
            }
            catch (Exception)
            {

            }
        }
        #endregion
        /// <summary>
        /// 消息接收测试
        /// </summary>
        /// <param name="xmlMsg"></param>
        private void ResponseText(ExmlMsg xmlMsg)
         {     
            int nowtime =Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd"));
            string msg = "";
            msg = getText(xmlMsg);
            string resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
            Response.Write(resxml);

        } 
        private string getText(ExmlMsg xmlMsg)
          {
             string con = xmlMsg.Content.Trim();
             StringBuilder retsb = new StringBuilder(200);
             retsb.Append("这是测试返回");
             retsb.Append("接收到的消息："+ xmlMsg.Content);
             retsb.Append("用户的OPEANID："+ xmlMsg.FromUserName);
            return retsb.ToString();
         }

        public void WriteMess(string mess)
        {

            string realPath = Server.MapPath("//rizhi.txt");//真正的地址
            FileStream fsWriter = null;//公开以文件为主的流
            if (!System.IO.File.Exists(realPath))
            {
                fsWriter = new FileStream(realPath, FileMode.Create);
            }
            else
            {
                fsWriter = new FileStream(realPath, FileMode.Append);
            }
            StreamWriter sw = new StreamWriter(fsWriter);//实现一个类，向流中写入字符
            sw.WriteLine(mess);//写入流
            sw.Close();//类关闭
            fsWriter.Close();//流关闭
        }
    }
}
